package com.yuanjun.product.vo.base;


import com.fasterxml.jackson.annotation.JsonIgnore;

import java.io.Serializable;

public class BaseResult<T> implements Serializable {

    private static final int CODE_OK = 200;
    /**
     * 400 业务错误，将返回消息提示给用户
     */
    private int code;
    private String message;
    private String token;
    private T data;

    private BaseResult() {
    }

    public BaseResult(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public BaseResult(int code, String message, String token, T data) {
        this.code = code;
        this.message = message;
        this.token = token;
        this.data = data;
    }

    public static <T> BaseResult createOk(String token, T data) {
        return new BaseResult<>(CODE_OK, "", token, data);
    }

    public static BaseResult createToken(String token) {
        return new BaseResult<>(CODE_OK, "", token, "");
    }

    public static <T> BaseResult createOk(T data) {
        return createOk(data, "");
    }

    public static <T> BaseResult createOk(T data, String msg) {
        BaseResult<T> result = new BaseResult<>();
        result.data = data;
        result.code = CODE_OK;
        result.message = msg;
        return result;
    }

    public static <T> BaseResult createFail(int code, T messageOrData) {
        BaseResult<T> result = new BaseResult<>();
        result.code = code;
        if (messageOrData instanceof CharSequence) {
            result.message = messageOrData.toString();
        } else {
            result.data = messageOrData;
        }
        return result;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @JsonIgnore
    public boolean isOk() {
        return code == CODE_OK;
    }
}